﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using DG.Common.EF.Reflection;

namespace DG.Common.EF.WPF
{
    public partial class EntityViewerWindow : Window
    {
        public EntityViewerWindow(EntityViewerModel vm)
        {
            InitializeComponent();

            DataContext = vm;

            vm.Finished += Close;
            vm.MessageSent += s => MessageBox.Show(s);

        }
    }
    public class TypeTemplateSelector : DataTemplateSelector
    {
        public DataTemplate ComboBoxTemplate { get; set; }
        public DataTemplate EnumTemplate { get; set; }
        public DataTemplate StringTemplate { get; set; }
        public DataTemplate ReadOnlyTemplate { get; set; }
        public DataTemplate BooleanTemplate { get; set; }
        public DataTemplate DateTimeTemplate { get; set; }
        public DataTemplate NumericTemplate { get; set; }
        public DataTemplate DecimalTemplate { get; set; }

        public DataTemplate PasswordTemplate { get; set; }

        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            if (item == null) return null;
            var prop = (IEntityViewerProperty)item;

            if (prop.IsReadOnly) return ReadOnlyTemplate;
            if (prop.EntityPropertyConceptualInfo.IsEnum) return EnumTemplate;
            if (prop.EntityPropertyConceptualInfo.IsNavigation) return ComboBoxTemplate;

            var type = prop.EntityPropertyConceptualInfo.Type;

            var isNullable = (type.IsGenericType) && (type.GetGenericTypeDefinition() == typeof(Nullable<>));
            if (isNullable)
            {
                type = type.GetGenericArguments()[0];
            }

            if (type == typeof(decimal)) return DecimalTemplate;
            if (type == typeof(double)) return DecimalTemplate;
            if (type == typeof(float)) return DecimalTemplate;
            if (type == typeof(long)) return NumericTemplate;
            if (type == typeof(int)) return NumericTemplate;
            if (type == typeof(sbyte)) return NumericTemplate;
            if (type == typeof(byte)) return NumericTemplate;
            if (type == typeof(bool)) return BooleanTemplate;
            if (type == typeof(DateTime)) return DateTimeTemplate;
            if (type == typeof(string) && prop.EntityPropertyConceptualInfo.Property.GetCustomAttributes(typeof(DataTypeAttribute), true).Any()) 
                return PasswordTemplate;
            if (type == typeof (string)) return StringTemplate;
            

            return StringTemplate;
        }
    }
}
